<template>
  <div class="article-list" ref="articleList">
    <van-pull-refresh :success-duration="1500"
      success-text="刷新成功" v-model="isRefreshLoading" @refresh="onRefresh">
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        :error.sync="error"
        error-text="请求失败，点击重新加载"
        @load="onLoad"
      >
        <van-cell v-for="item in list" :key="item.art_id" :title="item.title" />
        <article-item
          v-for="(article, index) in list"
          :key="index"
          :article="article"
        />
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { getArticles } from "@/api/article";
import articleItem from "./article-item.vue";
import {throttle} from 'lodash'

export default {
  name: "ArticleList",
  components: { articleItem },
  props: {
    channel: {
      type: Object,
      required: true,
    },
  },
  data() {
    return {
      list: [],
      loading: false,
      finished: false,
      error: false,
      timestamp: null,
      isRefreshLoading: false,
    };
  },
  methods: {
    async onLoad() {
      try {
        const { data } = await getArticles({
          channel_id: this.channel.id,
          timestamp: this.timestamp || Date.now(),
          with_top: 1,
        });
        this.list.push(...data.results);
        this.loading = false;
        if (data.pre_timestamp) {
          this.timestamp = data.pre_timestamp;
        } else {
          this.finished = true;
        }
      } catch (error) {
        this.error = true;
        this.loading = false;
      }
    },
    onRefresh() {
      this.list=[],
      this.loading=true
      this.finished =false,
      this.error=false,
      this.timestamp=null,
      this.onLoad()
    this.isRefreshLoading=false
    },
  },
  mounted(){
      this.$refs.articleList.addEventListener('scroll', throttle(function () {
      this.setAttribute('top', this.scrollTop)
    }, 400))
  },
  activated(){
  const Top = this.$refs.articleList.getAttribute('top')
    this.$refs.articleList.scrollTop = Top
  }
};
</script>

<style lang="less" scoped>
.article-list {
  margin-top: 88px;
  height: calc(100vh - 188px);
  overflow-y: auto;
}
</style>>
